//
//  CountDownButton.swift
//  CosClub
//
//  Created by iOS on 2020/4/23.
//  Copyright © 2020 ios. All rights reserved.
//

import UIKit

public class CountDownButton: UIButton {
    //倒计时启动
    
    public var normalTitle: String = "获取验证码"
    public var countDownTitle: String = "秒后重发"
    public var codeTimer = DispatchSource.makeTimerSource(queue:DispatchQueue.global())
    
    private var hasBeenSet = false
    
    public var remainingCount: Int = 0 {
        
        willSet {
            setTitle("\(newValue)\(countDownTitle)", for: .normal)

            if newValue <= 0 {
                setTitle("\(normalTitle)", for: .normal)
            }
        }
    }
    /// 开始倒计时
    public func countDown(count: Int){
        
        firstSet()
        // 倒计时开始,禁止点击事件
        remainingCount = count
        isEnabled = false
        // 启动时间源
        codeTimer.resume()
        
    }
    
    /// 取消倒计时
    public func countdownCancel() {
            
        codeTimer.suspend()
       
        // 返回主线程
        DispatchQueue.main.async {
            
            self.isEnabled = true
            if self.titleLabel?.text?.count != 0 {
                self.setTitle("获取验证码", for: .normal)
            }
        }
    }
    
    public func firstSet() {
        if self.hasBeenSet {
            return
        }
        hasBeenSet = true
        // 设定这个时间源是每秒循环一次，立即开始
        codeTimer.schedule(deadline: .now(), repeating: .seconds(1))
        // 设定时间源的触发事件
        codeTimer.setEventHandler(handler: {
          
            DispatchQueue.main.async {
                
                // 每秒计时一次
                
                self.remainingCount -= 1
                
                // 时间到了取消时间源
                
                if self.remainingCount <= 0 {
                    
                    self.isEnabled = true
                    self.codeTimer.suspend()
                }
            }
        })
    }
}
